<template>
  <div class="home">
    <h1 class="welcome-title">欢迎使用电影推荐系统</h1>
    <h2 class="section-title">热门电影</h2>
    
    <div v-if="movieStore.loading && !movieStore.trendingMovies.length" class="loading-wrapper">
      <el-skeleton :rows="3" animated />
    </div>

    <el-row v-else-if="movieStore.error">
      <el-col :span="24">
        <el-alert :title="movieStore.error" type="error" />
      </el-col>
    </el-row>

    <el-row v-else :gutter="16">
      <el-col v-for="movie in movieStore.trendingMovies" 
              :key="movie.id"
              :xs="12" 
              :sm="8" 
              :md="6" 
              :lg="4" 
              :xl="4">
        <MovieCard :movie="movie" />
      </el-col>
    </el-row>

    <!-- 加载更多区域 -->
    <div v-if="movieStore.trendingMovies.length > 0" 
         class="load-more" 
         v-loading="movieStore.loading">
      <p v-if="!movieStore.hasMore" class="no-more">没有更多电影了</p>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { useMovieStore } from '@/stores/movie'
import MovieCard from '@/components/MovieCard.vue'

const movieStore = useMovieStore()

// 处理滚动加载
const handleScroll = () => {
  const scrollHeight = document.documentElement.scrollHeight
  const scrollTop = document.documentElement.scrollTop
  const clientHeight = document.documentElement.clientHeight
  
  // 当距离底部100px时开始加载更多
  if (scrollHeight - scrollTop - clientHeight <= 100 && !movieStore.loading) {
    movieStore.fetchTrendingMovies(true)
  }
}

onMounted(() => {
  movieStore.fetchTrendingMovies()
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.home {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.welcome-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
}

.section-title {
  font-size: 20px;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.loading-wrapper {
  padding: 20px;
}

.load-more {
  text-align: center;
  padding: 20px 0;
  min-height: 60px;
}

.no-more {
  color: #909399;
  font-size: 14px;
}

@media (max-width: 768px) {
  .home {
    padding: 10px;
  }
}
</style> 